package com.github.serezhka.airplay.player.gstreamer;

import com.csmk.control.MKSApi;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

@Slf4j
public class GstKeyListener implements KeyListener {

    private final MKSApi mksApi;

    public GstKeyListener(MKSApi mksApi) {
        this.mksApi = mksApi;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.isControlDown()  && e.getKeyCode() == KeyEvent.VK_C) {
            // 要复制到剪贴板的文本
            String text = "这是要复制的文本内容";
            // 将文本封装为剪贴板内容
            StringSelection stringSelection = new StringSelection(text);
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        }else if(e.isControlDown()  && e.getKeyCode() == KeyEvent.VK_V){
            try{
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                // 获取剪贴板内容
                if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
                    String text = (String) clipboard.getData(DataFlavor.stringFlavor);
                    mksApi.inputText(text);
                    log.info("从剪贴板获取的文本内容:{}",text);
                } else {
                    log.info("剪贴板中没有文本内容");
                }
            }catch (Exception ex){
                log.error("粘贴异常");
                ex.printStackTrace();
            }
        }else if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE){
            mksApi.delText();
        }else if(isPrintableKey(e.getKeyChar())){
            mksApi.inputText(String.valueOf(e.getKeyChar()));
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    private static boolean isPrintableKey(char keyChar) {
        // 0-9
        if (keyChar >= '0' && keyChar <= '9') {
            return true;
        }
        // a-z
        if (keyChar >= 'a' && keyChar <= 'z') {
            return true;
        }
        // A-Z
        if (keyChar >= 'A' && keyChar <= 'Z') {
            return true;
        }
        // 特殊符号 (ASCII 范围内可打印的字符)
        if (keyChar >= 33 && keyChar <= 126) {
            return true;
        }
        return false;
    }
}
